<template>
  <div style="width: 100%; height:100%;display: flex; justify-content: center; padding: 10px 0" v-loading="isLoading">
    <el-space wrap fill-ratio="35" direction="horizontal" style="width: 87%">
      <el-card v-for="card in cardList" :key="card.id" style="width: 650px; height: 260px">
        <template #header>
          <div style="display: flex; justify-content: space-between">
            任务编号:{{ card.id }}
            <el-tag :type="RecycleStatusOptions.find((item) => item.value === card.status)?.type">
              {{ RecycleStatusOptions.find((item) => item.value === card.status)?.label }}
            </el-tag>
          </div>
        </template>
        <el-form :model="card" label-width="70" inline>
          <el-form-item label="用户名">
            <el-tag type="info" effect="plain">{{ card.username }}</el-tag>
          </el-form-item>
          <el-form-item label="联系方式">
            <el-tag type="info" effect="plain">{{ card.mobile }}</el-tag>
          </el-form-item>
          <el-form-item label="预约时间">
            <el-tag type="info" effect="plain">{{ card.recycleTime }}</el-tag>
          </el-form-item>
          <el-form-item label="地址">
            <el-tag type="info" effect="plain">{{ card.area.join(" ") + card.address }}</el-tag>
          </el-form-item>
          <el-form-item label="垃圾列表">
            <el-link type="primary" icon="Tickets" @click="openWasteListDrawer(card.wasteList)">
              <span style="padding: 0 5px">{{ card.wasteList.length }}项</span>
            </el-link>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" v-if="card.status == '1'" style="float:right"
            @click="handleOpenRecycleDialog(card.id)">回收确认</el-button>
        </template>
      </el-card>
    </el-space>
  </div>
  <!--垃圾列表-->
  <el-drawer v-model="wasteListDrawer" :with-header="false" @close="handleCloseWasteDrawer()">
    <el-space v-for="waste in wasteList" :key="waste.id" style="
        width: 100%;
        border: #a9a9a9 1px solid;
        border-radius: 5px;
        padding: 5px;
        margin: 5px 0;
      ">
      <!-- 图片预览 -->
      <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[waste.fileUrl]"
        style="width: 200px; height: 150px" :src="waste.fileUrl" fit="cover" />

      <!-- 垃圾类型选择 -->
      <el-space direction="vertical" :size="10">
        <el-select filterable v-model="waste.typeId" placeholder="请选择垃圾类型" disabled>
          <el-option v-for="item in wasteTypesOptions" :key="item.id" :label="item.typeName" :value="item.id" />
        </el-select>
        <el-input v-model="waste.weight" disabled>
          <template #suffix>千克(kg)</template>
        </el-input>
      </el-space>
    </el-space>
  </el-drawer>

  <!--确认框-->
  <el-dialog v-model="recycleConfirmDialog.visible" style="width:650px" align-center
    @close="handleCloseRecycleDialog()">
    <el-form ref="confirmRef" :model="recycleConfirmDialog" label-width="80px" :rules="confirmRules"
      :validate-on-rule-change="false" :validate-on-value-change="true">
      <el-form-item label="回收结果" prop="auditStatus">
        <el-select v-model="recycleConfirmDialog.auditStatus" placeholder="请选择" style="width: 150px;">
          <el-option label="通过" value="0" />
          <el-option label="驳回" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="垃圾列表" v-if="recycleConfirmDialog.auditStatus == '0'" prop="wasteList">
        <div style="display: flex; flex-direction: column">
          <el-scrollbar max-height="280px">
            <!--垃圾列表（图片、类型、重量）-->
            <el-space fill style="margin-bottom: 10px">
              <div v-for="(waste, index) in recycleConfirmDialog.wasteList" :key="index">
                <el-space>
                  <!-- 上传图片 -->
                  <SingleImageUpload v-if="recycleConfirmDialog.status == '1'" v-model="waste.fileUrl" />
                  <el-image v-else :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[waste.fileUrl]"
                    style="width: 100px; height: 80px" :src="waste.fileUrl" fit="cover" />

                  <!-- 垃圾类型选择 -->
                  <el-space direction="vertical" alignment="start" :size="10">
                    <el-space>
                      <el-select filterable v-model="waste.typeId" placeholder="请选择垃圾类型" style="width: 200px"
                        :prop="`wasteList.${index}.typeId`">
                        <el-option v-for="item in wasteTypesOptions" :key="item.id" :label="item.typeName"
                          :value="item.id" />
                      </el-select>
                      <el-input-number v-model="waste.weight" :precision="2" :step="0.1" placeholder=""
                        :prop="`wasteList.${index}.weight`" style="width: 200px">
                        <template #suffix>千克(kg)</template>
                      </el-input-number>
                    </el-space>
                    <el-space>
                      回收收益:
                      <el-text style="padding-left:10px">
                        {{ waste.actualPrice ? `${waste.actualPrice}元` : '待计算' }}
                      </el-text>
                    </el-space>
                  </el-space>
                  <!-- 删除按钮 -->
                  <el-icon @click="deleteWasteItem(index)" style="cursor: pointer" size="20"
                    v-if="recycleConfirmDialog.status == '1'">
                    <Remove />
                  </el-icon>
                </el-space>
              </div>
            </el-space>
          </el-scrollbar>
          <el-icon style="cursor: pointer; float: left" size="20" @click="addWasteItem()"
            v-if="recycleConfirmDialog.status == '1'">
            <CirclePlus />
          </el-icon>
          <!--一键计算，显示收益-->
          <div v-if="recycleConfirmDialog.wasteList.length"
            style="width:100%;display:flex;justify-content:space-between">
            <el-link type="primary" :underline="false"
              @click="calculatePrice(recycleConfirmDialog.wasteList)">一键计算</el-link>
            <el-text style="padding-right:10px">
              回收总收益:{{ calculateResult.totalPrice }} 元
            </el-text>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="驳回原因" v-if="recycleConfirmDialog.auditStatus == '1'" prop=rejectReason>
        <el-input v-model="recycleConfirmDialog.rejectReason" type="textarea" resize="none"
          :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入驳回原因">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center;">
        <el-button @click="handleCloseRecycleDialog()">取消</el-button>
        <el-button type="primary" @click="handleRecycleBtn()">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
defineOptions({
  name: "RecycleTask",
  inheritAttrs: false,
});

import { ref } from "vue";
import TaskAPI from "@/api/system/task";
import { useUserStore } from "@/store";
import RecycleRequestAPI from "@/api/system/recycle-request.js";
import { RecycleStatusOptions } from '@/enums/RecycleStatusEnum.ts';

const userStore = useUserStore();

/**
 * 查询卡片数据列表
 */
const isLoading = ref(false);
const cardList = ref([]);
const handleQuery = () => {
  const userId = userStore.userInfo.userId;
  if (userId && !isLoading.value) {
    isLoading.value = true;
    TaskAPI.getCourierTaskList(userId)
      .then(data => cardList.value = data)
      .finally(() => isLoading.value = false);
  }
};

//打开回收弹框
const recycleConfirmDialog = reactive({
  visible: false,
  id: "",
  requestId: "",
  status: "",
  auditStatus: "",
  rejectReason: "",
  wasteList: [],
})
const confirmRef = ref(null)
const confirmRules = reactive({
  auditStatus: [{
    required: true,
    message: '请选择审核结果',
    trigger: 'change'
  }],
  wasteList: {
    required: true,
    validator: (rule, value, callback) => {
      if (recycleConfirmDialog.auditStatus === '0' && value.length == 0) {
        callback(new Error('垃圾条目不能为空'))
      } else {
        //校验每个垃圾条目的数据
        value.forEach(item => {
          if (!item.typeId || !item.weight) {
            callback(new Error('垃圾条目的类别与重量不能为空'))
            return
          }
        })
        callback()
      }
    }
  },
  rejectReason: [{
    required: true,
    validator: (rule, value, callback) => {
      if (recycleConfirmDialog.auditStatus === '1' && !value) {
        callback(new Error('驳回原因必须填写'))
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }]
})
const handleOpenRecycleDialog = async (taskId) => {
  recycleConfirmDialog.visible = true;
  wasteTypesOptions.value = await RecycleRequestAPI.getAllWasteTypes();
  const card = await TaskAPI.getCourierTask(taskId);
  Object.assign(recycleConfirmDialog, card);
  confirmRef.value?.clearValidate()
};

const handleRecycleBtn = () => {
  confirmRef.value?.validate((valid) => {
    if (valid) {
      //一键计算
      if (calculateResult.totalPrice == 0.0) {
        ElMessage.warning("请先进行一键计算收益");
        return
      }
      // 提交审核
      TaskAPI.courierAuditTask({
        taskId: recycleConfirmDialog.id,
        requestId: recycleConfirmDialog.requestId,
        auditStatus: recycleConfirmDialog.auditStatus,
        rejectReason: recycleConfirmDialog.rejectReason,
        wasteList: recycleConfirmDialog.wasteList,
        expectReturn: calculateResult.totalPrice
      }).then(data => {
        if (data) {
          ElMessage.success("操作成功");
          handleCloseRecycleDialog()
          handleQuery();
        }
      })
    }
  })
}

const handleCloseRecycleDialog = () => {
  recycleConfirmDialog.visible = false;
  Object.assign(recycleConfirmDialog, {
    id: "",
    requestId: "",
    auditStatus: "",
    rejectReason: "",
    wasteList: []
  });
  confirmRef.value?.clearValidate();
  calculateResult.priceMap = {};
  calculateResult.totalPrice = 0.0;
}
/**
 * 查看垃圾列表抽屉
 */
const wasteListDrawer = ref(false);
const wasteList = ref([]);
const wasteTypesOptions = ref([]);
const openWasteListDrawer = async (list) => {
  wasteListDrawer.value = true;
  wasteTypesOptions.value = await RecycleRequestAPI.getAllWasteTypes();
  if (list?.length) {
    wasteList.value = list;
  }
};
//关闭垃圾列表时回调
const handleCloseWasteDrawer = () => {
  wasteList.value = [];
};

/**
 * 垃圾列表管理
 */
const addWasteItem = () => {
  const newWasteItem = {
    id: "",
    typeId: "",
    fileUrl: "",
    weight: undefined,
    actualPrice: 0.0,
  };

  recycleConfirmDialog.wasteList.push(newWasteItem);
};
const deleteWasteItem = async (index) => {
  if (recycleConfirmDialog.wasteList[index].fileUrl) {
    await FileAPI.delete(recycleConfirmDialog.wasteList[index].fileUrl);
  }
  recycleConfirmDialog.wasteList.splice(index, 1);
};


//一键计算价格收益
const calculateResult = reactive({
  priceMap: {},
  totalPrice: 0.0
})
const calculatePrice = async (wasteList) => {
  const data = await TaskAPI.calculatePriceAPI(wasteList);
  //预计总收益
  calculateResult.priceMap = data.priceMap;
  calculateResult.totalPrice = data.totalPrice;

  //赋值收益价格
  wasteList.forEach(item => {
    item.actualPrice = calculateResult.priceMap[item.typeId]
  })
}
onMounted(() => {
  handleQuery();
});
</script>
<style scoped></style>
